import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
  AfterLoad, ManyToMany, JoinTable
} from "typeorm"
import { Article } from "./Article";
import { Comment } from "./Comment";

import moment from "moment/moment"
import { Post } from "./Post";

moment.locale('zh-cn')

export enum Role {
  ADMIN = 100, // 管理员
  USER = 1, // 普通用户
  TEACHER = 2, // 教师
}

@Entity()
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string

  @Column({ length: 15, comment: "用户名" })
  username: string // 用户名

  @Column({ unique: true, comment: "手机号" })
  phoneNumber: string // 手机号

  @Column({ nullable: true, comment: "头像" })
  avatar: string // 头像

  @Column({ type: "enum", enum: Role, default: Role.USER, comment: "角色" })
  role: Role // 角色

  @Column({ default: 0, comment: "积分" })
  score: number // 积分

  @Column({ nullable: true, comment: "华为用户唯一ID" })
  unionId: string // 用户唯一标识

  @ManyToMany(() => User, { createForeignKeyConstraints: false })
  followers: User[] // 被关注的用户（被其他人关注）

  @ManyToMany(() => User, { createForeignKeyConstraints: false })
  @JoinTable({
    name: 'user_follower',
    joinColumn: { name: 'follower_id' },
    inverseJoinColumn: { name: 'following_id' }
  })
  followings: User[] // 关注的用户（主动关注其他人）

  @OneToMany(() => Article, (article) => article.author)
  articles: Article[] // 发表的文章

  @OneToMany(() => Post, (post) => post.author)
  posts: Post[] // 发表的帖子

  @OneToMany(() => Comment, (comment) => comment.commenter)
  comments: Comment[] // 发表的评论

  @CreateDateColumn()
  createdAt: Date | string; // 创建时间

  @UpdateDateColumn()
  updatedAt: Date | string; // 更新时间

  @AfterLoad()
  formatDate() {
    this.createdAt = moment(this.createdAt).format('LL')
    this.updatedAt = moment(this.updatedAt).format('LL')
  }
}